<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="添加编码" v-model="visible" align-center width="800px" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top">
      <el-form-item label="编码类型" prop="type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <el-radio-group v-model="form.type">
          <el-radio v-for="(d, i) in options.type" :key="i" :label="d.value">{{ d.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="可用平台" prop="platform_ids" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" class="mr-6"
          @change="handleCheckAllChange">全部平台</el-checkbox>
        <el-checkbox-group v-model="form.platform_ids" @change="handleCheckedChange">
          <el-checkbox v-for="(d, i) in options.platform" :key="i" :label="d.value">{{ d.label }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="可用部门">
        <VCascader v-model="form.department_id" placeholder="请选择" multiple :type=1 class="w-full" />
      </el-form-item>
      <el-form-item label="商品编码" prop="code" :error="errorMsg"
        :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
        <div class="grid grid-cols-5 gap-x-3 w-full">
          <el-input v-model="form.code" type="textarea" :autosize="{ minRows: 5, maxRows: 200 }" placeholder="请输入"
            class="col-span-3" />
          <div class="col-span-2 text-orange-400 text-md">
            UPC仅支持输入8位、12位或13位的数字<br />

            EAN仅支持输入8位或13位的数字<br />

            ISBN仅支持输入10位或13位的数字
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const success = ref(false)
let loadings = reactive({})
const errorMsg = ref('')

// 表单处理
const formRef = ref()
const form = ref({})

const checkAll = ref(false)
const isIndeterminate = ref(false)
const handleCheckAllChange = (val) => {
  form.value.platform_ids = val ? props.options.platform.map(d => d.value) : []
  isIndeterminate.value = false
}
const handleCheckedChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === props.options.platform.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < props.options.platform.length
}

// 打开弹窗
const open = async (id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = { type: 1 }
  loadings = reactive({})
  errorMsg.value = ''
  success.value = false
  checkAll.value = false
  isIndeterminate.value = false
  visible.value = true
  formRef?.value?.clearValidate()
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  success.value && emit('success')
}
// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  errorMsg.value = ''
  form.value.code = form.value.code.split('\n').map(d => {
    if (/\*$/.test(d)) d = d.replace('*', '')
    return d
  }).join('\n')
  api.create(form.value).then(res => {
    const { code, data, message } = res
    if (code === 200) {
      ElMessage.success('保存成功')
      success.value = true
      close()
    } else {
      form.value.code = form.value.code.split('\n').map(d => {
        if (data.includes(d)) d += '*'
        return d
      }).join('\n')
      errorMsg.value = message
    }
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>